package thread;

/**
 *   线程死锁
 * @author fix
 * 产生的原因：
 *  A线程锁住资源AA 后，去尝试锁住 资源BB
 *  B线程锁住资源BB 后，去尝试锁住 资源AA   两个线程都不释放资源，程序锁死都不能结束
 
       锁this 和   锁对象的区别？？
 
 */

class Keys{
	public static String gold="金钥匙";
	public static String silver="银钥匙";
}

class Lock1 implements Runnable{
	
    public void run(){
        try{
            System.out.println("Lock1 running");
             
                synchronized(Keys.gold){
                    System.out.println("Lock1 lock 金钥匙");
                    Thread.sleep(3000);//获取obj1后先等一会儿，让Lock2有足够的时间锁住obj2
                    synchronized(Keys.silver){
                        System.out.println("Lock1 lock 银钥匙");
                        System.out.println("恭喜Lock1芝麻开门");
                    }
                }
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

class Lock2 implements Runnable{
	
    public void run(){
        try{
            System.out.println("Lock2 running");
             
                synchronized(Keys.silver){
                    System.out.println("Lock2 lock 银钥匙");
                    Thread.sleep(3000);//获取obj1后先等一会儿，让Lock2有足够的时间锁住obj2
                    synchronized(Keys.gold){
                        System.out.println("Lock2 lock 金钥匙");
                        System.out.println("恭喜Lock2芝麻开门");
                    }
                }
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

public class Test7 {
	
	public static void main(String[] args) {
		Thread a = new Thread(new Lock1());
        Thread b = new Thread(new Lock2());
        a.start();
        b.start();
	}

}
